<template>
  <div class="app-wrapper">
    <headerTitle
      :titleList="titleList"
    />
    <div class="app-container"  ref="block">
      <div class="containerMain">
        <div class="search-item">
          <div class="item-list">
            <div class="item-con">
              <span>时间</span>
              <el-date-picker
                  v-model="timeValue"
                  unlink-panels
                  size="mini"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['00:00:00', '23:59:59']"
                >
                </el-date-picker>
            </div>
            <div class="item-con">
              <span>坐席ID</span>
              <el-input
                style="width: 200px"
                size="mini"
                v-model="searchform.agentId"
                placeholder="请输入坐席ID"
              ></el-input>
            </div>
            <div class="item-con">
              <span>坐席姓名</span>
              <el-input
                style="width: 200px"
                size="mini"
                v-model="searchform.agentName"
                placeholder="请输入坐席姓名"
              ></el-input>
            </div>
            <div class="item-con">
              <span>坐席视讯号</span>
              <el-input
                style="width: 200px"
                size="mini"
                v-model="searchform.agentVideoNum"
                placeholder="请输入坐席视讯号"
              ></el-input>
            </div>
            <div class="item-con">
              <span>技能组ID</span>
              <el-select
                size="mini"
                clearable
                v-model="searchform.skillId"
                placeholder="全部"
              >
                <el-option
                  v-for="(item, index) in skillGroupList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>

          </div>
          <div class="item-btn">
            <el-button
              class="kyeup_search_btn"
              type="primary"
              size="mini"
              @click="() => fetchData()"
              >搜索</el-button
            >
            <el-button type="default" size="mini" @click="() => reset()"
              >重置</el-button
            >
          </div>
        </div>
        <div class="container">
          <div class="div-table">
            <el-table
              :header-cell-style="headerStyle"
              :data="list"
              element-loading-text="Loading"
              fit
              size="mini"
              highlight-current-row
              :height="tableHeight"
            >
              <el-table-column label="坐席ID">
                <template slot-scope="scope">{{ scope.row.agentId }}</template>
              </el-table-column>
              <el-table-column label="坐席姓名">
                <template slot-scope="scope">{{
                  scope.row.agentName
                }}</template>
              </el-table-column>
              <el-table-column label="坐席视讯号">
                <template slot-scope="scope">{{ scope.row.agentVideoNum }}</template>
              </el-table-column>
              <el-table-column label="技能组">
                <template slot-scope="scope">{{
                  scope.row.skillName
                }}</template>
              </el-table-column>

              <el-table-column label="通话次数">
                <template slot-scope="scope">{{
                  scope.row.callNumTimes
                }}</template>
              </el-table-column>
              <el-table-column label="通话总时长">
                <template slot-scope="scope">{{
                  scope.row.callTotalDurationStr
                }}</template>
              </el-table-column>
              <el-table-column label="平均通话时长">
                <template slot-scope="scope">{{
                  scope.row.callAvgDurationStr
                }}</template>
              </el-table-column>
              <!-- <el-table-column label="参会人标识">
                <template slot-scope="scope">{{
                  scope.row.agentId
                }}</template>
              </el-table-column>
              <el-table-column label="参会人姓名">
                <template slot-scope="scope">{{
                  scope.row.agentName
                }}</template>
              </el-table-column> -->
              <!-- <el-table-column label="操作" width="200px">
                <template slot-scope="scope">
                  <el-button type="text" @click="() => viewAttendee(scope.row)"
                    >参会人</el-button
                  >
                  <el-button type="text" @click="() => viewDetail(scope.row)"
                    >视频</el-button
                  >
                  <el-button type="text" @click="() => viewPhotoDetail(scope.row)"
                    >照片</el-button
                  >
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </div>

      </div>
    </div>
    <el-dialog title="参会人详情" :visible.sync="dialogTableVisible">
      <el-table :data="attendeeData">
        <el-table-column property="userId" label="参会人" width="150"></el-table-column>
        <el-table-column property="userType" label="参会人类型" width="150" :formatter="formatter"></el-table-column>
        <el-table-column property="joinTime" label="进入会议时间" width="200"></el-table-column>
        <el-table-column property="leaveTime" label="离开会议时间"></el-table-column>
      </el-table>
    </el-dialog>
    <pagination
      :exportShow="true"
      :type="'primary'"
      @handelExport="exportDetail"
      btnExport="导出"
      :pagination="pagination"
    />


  </div>
</template>

<script>

import moment from "moment";
import Pagination from "@/components/Pagination/index";
import HeaderTitle from "@/components/Headertitle/index";
import {
  fetchAgentList
} from "@/api/systemapi/agent";
import { fetchSeatPerformList, fetchSeatExport, fetchAllSkill,checkSeatExport,fetchAttendeeDetail } from "@/api/systemapi/video";//搜索  导出
import { pageParams } from "@/settings";

export default {
  components: {
    Pagination,
    HeaderTitle
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: "启用",
        2: "禁用",
      };
      return statusMap[status];
    },
  },
  data() {
    const TODAYSTART = moment().startOf('day').format('YYYY-MM-DD 00:00:00')
    const TODAYEND = moment().endOf('day').format('YYYY-MM-DD 23:59:59')
    return {
      titleList: [{ title: "坐席表现报表" }],
      dialogTableVisible: false,//参会人弹框控件
      attendeeData: [],
      list:[],
      skillList:[],
      tableHeight: "300", //表格默认高度
      timeValue: [TODAYSTART, TODAYEND],
      listLoading: true,
      skillGroupList: [],
      searchform: {
        rows: "10",
        page: "1",
        startTime:"",
        endTime:"",
        agentId:"",
        agentName:"",
        agentVideoNum:"",//坐席视讯号
        skillId:"",//技能组ID
        // ani:"",
        // agentId:"",
        // agentVideoNum:"",
        // customerVideoNum:"",
        // agentName:"",
        // sessionId:"",
        // meetingId:"",
        // urgentTitle:"",
        // stars:"",
        // endType:"",
        // skillId:"",
        // auditResult:"",
        // success:"",
      },
      // 分页
      pagination: pageParams
    };
  },
  watch: {
    // 分页
    "pagination.currentPage": function () {
      this.searchform.page = this.pagination.currentPage;
      this.fetchData();
    },
    "pagination.pageSize": function () {
      this.searchform.rows = this.pagination.pageSize;
      this.searchform.page = 1;
      this.fetchData();
    },
  },
  mounted() {
    this.$nextTick(() => {
      let self = this;
      this.tableHeight = this.$refs.block.offsetHeight - 220;
      window.onresize = () => {
        return (() => {
          this.tableHeight = this.$refs.block.offsetHeight - 220;
        })();
      };
    });
    //把技能组下拉框查出来
    //this.getSkillList();
    this.fetchSkillList();
    this.fetchData()
  },
  methods: {
    exportUser() {
      downloadUserInfo({
        exportType: 1,
        ...this.searchform,
      }).then((res) => {
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel",
        });
        let str = res.headers["content-disposition"].split(";")[1];
        // console.log(str,"str1111")
        if (str.indexOf("=") != -1) {
          var filename = decodeURI(str.slice(9));
        } else {
          var filename = decodeURI(str);
        }
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = filename; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      });
    },
    exportDemo() {
      downloadUserInfo({ exportType: 2 }).then((res) => {
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel",
        });
        let str = res.headers["content-disposition"].split(";")[1];
        // console.log(str,"str1111")
        if (str.indexOf("=") != -1) {
          var filename = decodeURI(str.slice(9));
        } else {
          var filename = decodeURI(str);
        }
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = filename; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      });
    },
    //表头背景颜色修改
    headerStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex == 0) {
        return "background:#F5F6FB;color:#666";
      }
    },
    getOrganList() {
      fetchOrganList().then((res) => {
        this.treeData = res.data;
      });
    },
    // 账号权限下拉
    getAccount() {
      fetchAccount().then((res) => {
        this.accountList = res.rows;
      });
    },
    // 点击树形节点 ，过滤列表坐席
    filterDepart(data) {
      let organId =
        this.searchform.organId.length > 0
          ? this.searchform.organId[this.searchform.organId.length - 1]
          : "";
      fetchAgentList({
        organTreeId: data.id,
        entNum: this.entNum,
        username: this.searchform.username,
        roleId: this.searchform.roleId,
        organId: organId,
        rows: this.searchform.rows,
        page: this.searchform.page,
      }).then((response) => {
        if (response.code == 0) {
          this.list = response.data.rows;
          this.pagination.total = response.data.records;
        } else {
          this.$message({
            type: "error",
            message: response.msg,
          });
        }
      });
    },
    // 重置搜索，刷新列表
    reset() {
      const TODAYSTART = moment().startOf('day').format('YYYY-MM-DD 00:00:00')
      const TODAYEND = moment().endOf('day').format('YYYY-MM-DD 23:59:59')
      this.timeValue = [TODAYSTART, TODAYEND],
      this.searchform = {
        startTime:this.timeValue[0],
        endTime:this.timeValue[1],
        agentId:"",
        agentName:"",
        agentVideoNum:"",//坐席视讯号
        skillId:"",//技能组ID
        // agentId:"",
        // agentVideoNum:"",
        // ani:"",
        // customerVideoNum:"",
        // agentName:"",
        // sessionId:"",
        // meetingId:"",
        // urgentTitle:"",
        // stars:"",
        // endType:"",
        // skillId:"",
        // auditResult:"",
        // success:"",
        rows: "10",
        page: "1",
      }
      // this.timeValue = [];
        // this.fetchData();
    },
    fetchSkillList() {//获取技能组ID
      fetchAllSkill({}).then((response) => {
        if (response.code == 0) {
          console.log(response,"技能组")
          this.skillGroupList = response.data;
        } else {
          this.$message({
            type: "error",
            message: response.msg,
          });
        }
      });
    },
    formatter(row, column) {
        return row.userType==1 ? "坐席" : "客户";
    },
    exportDetail() {//导出
        if (this.timeValue != null && this.timeValue.length > 0) {
          this.searchform.startTime = moment(this.timeValue[0]).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          this.searchform.endTime = moment(this.timeValue[1]).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        }
      checkSeatExport({...this.searchform}).then(res=>{//导出验证
        console.log(res,"daochuyanzhneg")
        if(res.code == 0){
          fetchSeatExport({ ...this.searchform }).then((res) => {
            console.log(res,"daochudaochu");
            let blob = new Blob([res.data], {
              type: "application/vnd.ms-excel",
            });
            console.log(res.headers["content-disposition"],"res.headers[")
            let str = res.headers["content-disposition"].split(";")[1];
            
            // console.log(str,"str1111")
            if (str.indexOf("=") != -1) {
              var filename = decodeURI(str.slice(9));
            } else {
              var filename = decodeURI(str);
            }
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = filename; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
          });
        }else{
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      })
      
    },

    fetchData() {//搜索
      console.log(this.timeValue,"this.timeValue");
      if (this.timeValue != null && this.timeValue.length > 0) {
          this.searchform.startTime = moment(this.timeValue[0]).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          this.searchform.endTime = moment(this.timeValue[1]).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        }
        console.log(this.searchform.startTime,"231232312");

      fetchSeatPerformList({...this.searchform}).then((response) => {
        if (response.code == 0) {
          this.list = response.data.records;
          this.pagination.total = response.data.total;
          console.log(response.data.records)
          console.log(this.list)
        } else {
          this.$message({
            type: "error",
            message: response.msg,
          });
        }
      });
    },
    fetchDetailData(id) {
      fetchDetail({id: id}).then((response) => {
        if (response.code == 0) {
          this.list = response.data;
          this.pagination.total = response.data.records;
          this.$router.push({ path: "/" });
        } else {
          this.$message({
            type: "error",
            message: response.msg,
          });
        }
      });
    },
    // 删除
    del(data) {
      this.$confirm("是否确定注销?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        fetchDel(data.id).then((response) => {
          if (response.code === 0) {
            this.fetchData();
            this.$message({
              message: "注销成功",
              type: "success",
            });
          } else {
            this.$message({
              message: response.msg,
              type: "error",
            });
          }
        });
      });
    },
    recover(data) {
      fetchRecover({ id: data.id, userType: "3" }).then((response) => {
        if (response.code === 0) {
          this.fetchData();
          this.$message({
            message: "恢复成功",
            type: "success",
          });
        } else {
          this.$message({
            message: response.msg,
            type: "error",
          });
        }
      });
    },
    resetPas(data) {
      this.$confirm("是否确定重置密码?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          fetchSetPsd({ id: data.id }).then((response) => {
            if (response.code === 0) {
              this.$message({
                message: "重置成功",
                type: "success",
              });
              this.fetchData();
            } else {
              this.$message({
                message: response.msg,
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置",
          });
        });
    },
    // 新增
    add(data) {
      this.$router.push({
        path: "/system/agent/detail",
        query: { type: 3},
      });
    },
    editBtn(data) {
      this.$router.push({
        path: "/system/agent/detail",
        query: { type: "2", id: data.id},
      });
    },
    viewFn(data) {
        this.$router.push({
        path: "/system/agent/detail",
        query: { type: "1", id: data.id},
      });
    },
    handelExport() {
      this.dialogVisible = true;
    },
    // 批量导入文件
    httpRequestExport(param) {
      let fileObj = param.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append("file", fileObj); // 文件对象
      fetchExport(fd).then((res) => {
        if (res.code == 0) {
          this.dialogVisible = false;
          this.fetchData();
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    submitUpload() {
      this.$refs.uploadBatch.submit();
    },
    // resetFileds() {
    //   // 重置校验
    //   if (this.$refs["ruleForm"]) {
    //     this.$refs["ruleForm"].resetFields();
    //   }
    // }
  },
};
</script>
<style lang="scss">
.tree-con {
  .el-tree-node__content {
    margin-bottom: 20px;
  }
}
</style>
<style lang="scss" scoped>
.containerMain {
  .search-item {
    padding: 20px 10px;
    font-size: 14px;
    color: #666;
    display: flex;
    justify-content: space-between;
    .item-list {
      display: flex;
      flex-wrap: wrap;
    }
    .item-con {
      display: flex;
      margin-right: 30px;
      margin-top: 20px;

      span {
        display: inline-block;
        line-height: 28px;
        margin-right: 10px;
      }
    }
    .item {
      width: 180px;
    }
  }
  .container {
    display: flex;
    flex-direction: row;
    .div-tree {
      width: 250px;
    }
    .div-table {
      flex: 1;
      width: 100%;
      overflow: hidden;
      .el-table {
        height: 100%;
        width: 100%;
        overflow: auto;
      }
    }
    .el-row {
      height: 300px;
      .el-col {
        height: 100%;
        .div-tree {
          height: 90%;
          .el-tree {
            height: 100%;
            overflow-y: auto;
          }
        }
      }
    }
  }
  .item-btn {
    margin-top: 20px;
    flex: 0 0 140px;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
